<template>
  <div class="car-match-box">
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="searchFilter" />

    <a-alert class="mb-5">
      {{ getAlertText(accountValue.value || form.sourceId) }}
    </a-alert>

    <table-index :table="form.staffMatchList">
      <template #table-summary>
        <div class="car-match-box-count">
          <div class="item">
            渠道员工数量：<span class="num">{{ form.staffMatchList.dataList.length }}</span>
          </div>
          <div class="item">
            未匹配员工数量：<span class="num">{{ getUnMatchStaffNum }}</span>
          </div>
        </div>
      </template>

      <template #channelStaffName="{ record, rowIndex }">
        <div v-if="record.id">
          <div>{{ record.channelStaffName }}</div>
          <div>{{ record.channelStaffPhone }}</div>
        </div>
        <page-form-item
          v-else
          size="1/2"
          style="margin-bottom: 0"
          :field="`staffMatchList.dataList.${rowIndex}.channelStaffName`"
          :rules="{ required: true, message: '请输入' }"
          required
        >
          <i-input v-model="record.channelStaffName" placeholder="请输入员工的姓名或账号" :max-length="100" />
        </page-form-item>
      </template>
      <template #relationStaffId="{ record, rowIndex }">
        <template v-if="record.status === 'view'">
          {{ record.relationStaffNamePhone }}
        </template>
        <page-form-item v-else style="margin-bottom: 0" size="1/2">
          <remote-select
            style="width: 100%"
            v-model="record.relationStaffId"
            :index="rowIndex"
            type="organ_staff_limit"
            @change="onStaffChange"
            :popupContainer="'.page-container'"
            :updateAtScroll="true"
            :scrollToClose="true"
          />
        </page-form-item>
      </template>
    </table-index>
  </div>
</template>

<script setup lang="ts">
  import { ref, inject, computed, reactive, onMounted } from 'vue'
  import { getChannelStaffList, syncAccount, deleteChannelStaff, syncAccountInfoStatus, saveChannelStaff } from '@/api/business/ota'
  import { useTable } from '@/hooks/table'
  import { useRoute } from 'vue-router'
  import { Message } from '@arco-design/web-vue'
  import getFuncOnLoopCondition from '@/utils/getFuncOnLoopCondition'

  const route = useRoute()
  const { params, query } = route
  console.log(route, 'staff-match')

  const props = defineProps({
    accountId: String,
    accountValue: {
      type: Object,
      default: () => ({}),
    },
  })

  // 各渠道提示内容
  const getAlertText = (options: any) => {
    switch (options) {
      case 2:
        return `悟空渠道的员工信息来源于【门店管理-门店列表-详情-门店人员】中的【姓名】字段`
      case 3:
        return `哈啰渠道的员工信息来源于【员工管理-员工账号】中的【姓名】字段`
      case 4:
        return `携程渠道的员工信息来源于【设置-用户管理】中的【昵称】字段`
      case 5:
        return `飞猪渠道的员工信息来源于【商家管理-商家账号-账号列表】中的【淘宝账号名(或飞猪店铺名)】字段`
      default:
        return '铁行渠道的员工信息来源于【员工管理】中的【姓名】字段'
    }
  }

  const formRef = inject<any>('formRef')
  const form = ref(inject<any>('form'))

  form.value.staffMatchList = useTable({
    tableLoading: false,
    pagination: false,
    columns: [
      {
        title: '渠道员工信息',
        dataIndex: 'channelStaffName',
        key: 'channelStaffName',
        slotName: 'channelStaffName',
      },
      {
        title: '商户员工信息',
        dataIndex: 'relationStaffId',
        key: 'relationStaffId',
        slotName: 'relationStaffId',
      },
    ],
    operates: [
      {
        label: '修改',
        show: (record: any) => record.id && record.status === 'view',
        method: (record: any, column: any, rowIndex: number) => {
          console.log(record, column, rowIndex)
          record.status = 'edit'
        },
      },
      {
        label: '保存',
        show: (record: any) => record.status === 'edit',
        method: (record: any, column: any, rowIndex: number) => {
          console.log(record, column, rowIndex)
          onSaveStaffMatch(record)
        },
      },
      {
        label: '删除',
        type: 'danger',
        method: (record: any, column: any, rowIndex: number) => {
          formRef.value.clearValidate()

          if (record.id) {
            onDeleteStaffMatch(record, rowIndex)
          } else {
            shadowCustomStaffList.list.splice(rowIndex, 1)
            form.value.staffMatchList.dataList = shadowCustomStaffList.list
          }
        },
      },
    ],
    buttons: [
      {
        // permission: 'svms:asstes:car:car-model:add',
        label: '同步员工',
        show: () => params.id && query.sourceId != '7' && query.sourceId != '8',
        method: () => {
          Message.info('同步中，请稍后')
          onSynStaffMatch()
        },
      },
      {
        type: 'primary',
        // permission: 'svms:asstes:car:car-model:add',
        icon: 'plus',
        label: '新增',
        method: () => {
          formRef.value.clearValidate()
          onAddStaffMatch()
        },
      },
    ],
    dataList: [],
  })

  const queryParam = reactive<any>({})
  const searchList = computed(() => {
    return [
      { label: '渠道员工姓名/账号', prop: 'channelStaffName', type: 'a-input', span: 1 },
      {
        label: '商户员工姓名',
        prop: 'relationStaffId',
        type: 'remote-select',
        attrs: {
          type: 'organ_staff_limit',
        },
      },
      {
        label: '商户员工配置',
        prop: 'sourceType',
        type: 'a-select',
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '0',
          },
        ],
      },
    ]
  })

  // 选择员工
  const onStaffChange = (value: any, option: any, index: number) => {
    form.value.staffMatchList.dataList[index].relationStaffNamePhone = option.namePhone
  }

  const onSaveStaffMatch = (record: any) => {
    saveChannelStaff(record).then((res: any) => {
      console.log('保存员工 saveChannelStaff', res)
      record.status = 'view'
    })
  }

  // 删除员工
  const onDeleteStaffMatch = (record: any, rowIndex: number) => {
    deleteChannelStaff({ id: record.id }).then((res: any) => {
      console.log('删除员工 deleteChannelStaff', res)

      shadowCustomStaffList.list.splice(rowIndex, 1)
      form.value.staffMatchList.dataList = shadowCustomStaffList.list

      queryParam.channelStaffName = ''
      queryParam.relationStaffId = ''
      queryParam.sourceType = ''
      loadData()
    })
  }

  const onAddStaffMatch = () => {
    searchFilter()
    shadowCustomStaffList.list.unshift({
      channelStaffName: '',
      relationStaffId: '',
      accountId: params.id || props.accountId,
    })

    form.value.staffMatchList.dataList = shadowCustomStaffList.list
    console.log('新增员工', form.value.staffMatchList.dataList)
  }

  // 未匹配员工数
  const getUnMatchStaffNum = computed(() => {
    return form.value.staffMatchList.dataList.filter((item: any) => !item.relationStaffId).length
  })

  const searchFilter = () => {
    form.value.staffMatchList.dataList = shadowCustomStaffList.list

    const result: any = []
    for (let i = 0; i < form.value.staffMatchList.dataList.length; i++) {
      // 过滤渠道员工
      if (queryParam.channelStaffName) {
        if (form.value.staffMatchList.dataList[i].channelStaffName !== queryParam.channelStaffName) {
          if (form.value.staffMatchList.dataList[i].channelStaffPhone !== queryParam.channelStaffName) {
            continue
          }
        }
      }

      // 过滤商户员工
      if (queryParam.relationStaffId) {
        console.log(queryParam.relationStaffId, 'relationStaffId')

        if (form.value.staffMatchList.dataList[i].relationStaffId !== +queryParam.relationStaffId) {
          continue
        }
      }

      // 过滤商户员工配置
      if (queryParam.sourceType) {
        if (queryParam.sourceType === '0') {
          if (form.value.staffMatchList.dataList[i].relationStaffId) {
            continue
          }
        }
        if (queryParam.sourceType === '1') {
          if (!form.value.staffMatchList.dataList[i].relationStaffId) {
            continue
          }
        }
      }

      result.push(form.value.staffMatchList.dataList[i])
    }

    form.value.staffMatchList.dataList = result

    const isEmpty = Object.keys(queryParam).every((key: any) => {
      return !queryParam[key]
    })
    if (isEmpty) {
      console.log('isEmpty', shadowCustomStaffList.list)

      form.value.staffMatchList.dataList = shadowCustomStaffList.list
    }
  }

  const copyCustomStaffList = ref()
  const shadowCustomStaffList = reactive<any>({
    list: [],
  })

  const loadData = () => {
    console.log('loadData', form.value)

    getChannelStaffList({ accountId: params.id || props.accountId }).then((res: any) => {
      res.result.forEach((item: any) => {
        item.status = 'view'
      })

      copyCustomStaffList.value = JSON.stringify(res.result)
      form.value.staffMatchList.dataList = res.result
      shadowCustomStaffList.list = form.value.staffMatchList.dataList.slice()
    })
  }

  // 检查同步账号信息状态
  const checkSyncAccountCondition = (response: any) => {
    return response.result === 0
  }

  // 同步员工
  const onSynStaffMatch = () => {
    syncAccount({ id: params.id || props.accountId }).then((res: any) => {
      // Message.success('同步成功')
      console.log('同步员工 syncAccountStore', res)
      const executor = async () => {
        const response = await syncAccountInfoStatus({ id: params.id || props.accountId })
        return response
      }
      const condition = checkSyncAccountCondition
      const delay = 1000
      getFuncOnLoopCondition(executor, condition, delay)
        .then(() => {
          loadData()
          queryParam.channelStaffName = ''
          queryParam.relationStaffId = ''
          queryParam.sourceType = ''
        })
        .catch((error: any) => {
          // Message.error(error.message)
          console.log('同步员工 error', error)
        })
    })
  }

  onMounted(() => {
    loadData()
  })

  defineExpose({
    loadData,
    copyCustomStaffList,
    shadowCustomStaffList,
    queryParam,
  })
</script>

<style lang="less" scoped>
  .car-match-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .list-search-wrapper {
      width: 100%;
    }
    &__empty {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .arco-icon-empty {
        margin-bottom: 4px;
        color: rgba(216, 216, 216, 1);
      }

      span {
        font-size: 12px;
        font-weight: 400;
        margin-bottom: 8px;
        color: rgba(216, 216, 216, 1);
      }
    }

    &-count {
      width: 100%;
      display: flex;
      font-size: 14px;
      font-weight: 400;
      color: #4e5969;

      .item {
        display: flex;
        align-items: center;
        margin-right: 29px;

        &:last-child {
          margin-right: 0;
        }
      }
      .num {
        color: #1890ff;
      }
    }

    .btn-list {
      position: absolute;
      right: -190px;
      width: 190px;
      padding-left: 29px;
      .btn-item {
        font-size: 14px;
        height: 32px;
        line-height: 32px;
        white-space: nowrap;
        outline: none;
        cursor: pointer;
        user-select: none;
        padding: 0 5px;
        icon {
          margin-right: 8px;
        }
        &.del {
          color: #ea0000;
        }
        &.new {
          color: #165dff;
        }
      }
    }
  }
</style>
